﻿// <copyright file="ExtensionSearch.cs" company="Edge Extensions Project">
// Copyright (c) 2009 All Rights Reserved
// </copyright>
// <author>Kevin Nessland</author>
// <email>kevinnessland@gmail.com</email>
// <date>2009-07-08</date>
// <summary>Assists with the searching of files by file extension.</summary>
namespace Edge.Extensions.Helpers
{
    using System;
    using System.Collections;
    using System.IO;

    /// <summary>
    /// Provides methods for searching files based upon their extension.
    /// </summary>
    public class ExtensionSearch
    {
        /// <summary>
        /// Used to store the list of found extensions.
        /// </summary>
        private ArrayList extensions;

        /// <summary>
        /// Determines whether or not to recursively search for extensions.
        /// </summary>
        private bool recursive;

        /// <summary>
        /// Initializes a new instance of the ExtensionSearch class.
        /// </summary>
        public ExtensionSearch()
        {
            this.extensions = ArrayList.Synchronized(new ArrayList());

            this.recursive = true;
        }

        /// <summary>
        /// Gets a list of extensions to include in the search.
        /// </summary>
        public ArrayList SearchExtensions
        {
            get { return this.extensions; }
        }

        /// <summary>
        /// Gets or sets a value indicating whether the search should recurse sub-directories.
        /// </summary>
        public bool Recursive
        {
            get { return this.recursive; }
            set { this.recursive = value; }
        }

        /// <summary>
        /// Performs a search of files by name.
        /// </summary>
        /// <param name="path">Directory path to search.</param>
        /// <returns>The results of the search.</returns>
        public FileInfo[] Search(string path)
        {
            DirectoryInfo root = new DirectoryInfo(path);
            ArrayList subFiles = new ArrayList();
            try
            {
                foreach (FileInfo file in root.GetFiles())
                {
                    if (this.extensions.Contains(file.Extension))
                    {
                        subFiles.Add(file);
                    }
                }

                if (this.recursive)
                {
                    foreach (DirectoryInfo directory in root.GetDirectories())
                    {
                        subFiles.AddRange(this.Search(directory.FullName));
                    }
                }
            }
            catch (UnauthorizedAccessException)
            {
                // might be nice to log this...
            }

            return (FileInfo[])subFiles.ToArray(typeof(FileInfo));
        }
    }
}
